// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require('moment')

cloud.init()

const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
  return new Promise((resolve, reject) => {

    db.collection('oil_prices').where({
      '_id': event.oil_id,
      'station_id': event.station_id
    }).orderBy('created_time', 'desc').limit(1).get().then(res => {

      // res.data 包含该记录的数据
      let old_price = res.data[0];
      if (old_price) {
        if (moment(res.data[0].created_time).format('YYYY-MM-DD') === moment(db.serverDate()).format('YYYY-MM-DD')) {
          db.collection('oil_prices').doc(event.oil_id).update({ //这里return 一直没写对
            data: {
              oils: event.oil_prices
            }
          }).then(result => {
            result.code = 200;
            result.body = res;
            resolve(result)
          })
        } else {
          db.collection('oil_prices').add({
            data: {
              auditing: false,
              created_time: db.serverDate(),
              oils: event.oil_prices,
              station_id: event.station_id ,
            }
          }).then(result => {
            resolve(result)
          }).catch(err => {
            resolve(err)

          })

        }

      }else{

        db.collection('oil_prices').add({
          data: {
            auditing: false,
            create_time: db.serverDate(),
            oils: event.oil_prices,
            station_id: event.station_id ,
          }
        }).then(result => {
          resolve(result)
        }).catch(err => {
          resolve(err)

        })
      }

    });

  })
  
  
}